package com.iwhalecloud.bss.kite.cucc.service.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.IOException;
import java.security.SecureRandom;

/**
 * Des加解密帮助类
 */
public class DesUtils {

    private byte[] desKey;

    public DesUtils(String desKey) {
        this.desKey = desKey.getBytes();
    }

    public byte[] desEncrypt(byte[] plainText) throws Exception {
        SecureRandom sr = new SecureRandom();
        byte rawKeyData[] = desKey;
        DESKeySpec dks = new DESKeySpec(rawKeyData);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key, sr);
        byte data[] = plainText;
        byte encryptedData[] = cipher.doFinal(data);
        return encryptedData;
    }

    public byte[] desDecrypt(byte[] encryptText) throws Exception {
        SecureRandom sr = new SecureRandom();
        byte rawKeyData[] = desKey;
        DESKeySpec dks = new DESKeySpec(rawKeyData);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, key, sr);
        byte encryptedData[] = encryptText;
        byte decryptedData[] = cipher.doFinal(encryptedData);
        return decryptedData;
    }

    public String encrypt(String input) throws Exception {
        return base64Encode(desEncrypt(input.getBytes("utf-8")));
    }

    public String decrypt(String input) throws Exception {
        byte[] result = base64Decode(input);
        return new String(desDecrypt(result), "utf-8");
    }

    public static String base64Encode(byte[] s) {
        if (s == null) {
            return null;
        }
        BASE64Encoder b = new sun.misc.BASE64Encoder();
        return b.encode(s);
    }

    public static byte[] base64Decode(String s) throws IOException {
        if (s == null) {
            return null;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b = decoder.decodeBuffer(s);
        return b;
    }

    public static void main(String[] args) throws Exception {
        DesUtils des = new DesUtils("lychee!23");
        String str = des.decrypt("11dxVLEsdI1FRh3cPbhQIQ0+Y40tiFyLrixmkOv2OnRO3w8xiPqrGYlgoW1pW0MwFJJn2WSPUAPQ"
            + "0tygXlbZtqMMwwRBQjRUT+LFcJqW70BcM0RwF32nabM5g9wAdOIltf8BmULSNkTgMo+4KcKKi3rU"
            + "c2UTNAFQ0A/CfqMeRRKPG1bBluZR+vExCnaPjRZTbY9xNRjAopwpWJTUkUF7DrhgHU2A2++Efiap"
            + "JJN1DE7R1ByRmR5f8EAkFgn3DnZx58UCqutaCyTw2oJ1+n7hIqz/Vnuia1Vf84Gee7xbMwtU83l7"
            + "LankP5SjWLdirFo55p6on3ldzmw=");

        System.out.println(str);

    }
}
